//
//  JTStartViewController+Step.m
//  JingRong_Safe_IDLFaceSDKDemoOC
//
//  Created by 万事如意 on 2025/9/1.
//  Copyright © 2025 Baidu. All rights reserved.
//

#import "JTStartViewController+Step.h"
#import "BDIDInfoCollectController.h"
#import "BDIDInfoAutoCollectController.h"
#import <BDFaceBaseKit/BDFaceBaseKit.h>
#import "BDFaceAdjustParamsTool.h"
#import "FaceParameterConfig.h"
#import <BDFaceLogicLayer/BDFaceLogicLayer.h>
#import "BDFaceVerificationController.h"
#import <AipOcrSdk/AipOcrSdk.h>
#import "BDFaceAdjustParamsFileManager.h"
#import "BDFaceForUploadImageViewController.h"

static NSString *BDTokenGetRequestUrl = @"http://10.138.55.237:8765/";


/// 超时时间设置
static NSUInteger BDFaceRequestTokenMaxTime = 60;


@implementation JTStartViewController (Step)

/**
 初始化人脸和OCR SDK
 */
- (void)initFaceServiceAndInfoCollectService {
    __weak typeof(self) this = self;
    /// 初始化 人脸识别Service
    self.logicService = [[BDFaceLogicService alloc] initWithController:self face:^{
        [this initFaceSDK];
    } ocr:^{
        [this initOcrSDK];
    }];
}

/*
 初始化人脸SDK
 */
- (void)initFaceSDK {
    //设置默认人脸参数
    
    BDFaceBaseKitParamsCustomConfigItem *paramsCustomConfigItem = [[BDFaceBaseKitParamsCustomConfigItem alloc] initWithParamsConfig];
    paramsCustomConfigItem.checkAgreeBtn = AdminInfo.shareInfo.hasAgree;
    paramsCustomConfigItem.blurThr = 0.9;
    paramsCustomConfigItem.numOfLiveness = 3;
    paramsCustomConfigItem.actionLiveSelectNum = 1;
    paramsCustomConfigItem.qualityLevel = 2;
    [[BDFaceBaseKitManager sharedInstance] setParamsCustomConfigItem:paramsCustomConfigItem];
    //设置默认UI参数
    if(paramsCustomConfigItem.colorSelectMode == BDFaceBlackType) {
        BDFaceBaseKitUICustomConfigItem *uiCustomConfigItem = [[BDFaceBaseKitUICustomConfigItem alloc] initWithBlackUIConfig];
        [[BDFaceBaseKitManager sharedInstance] setUiCustomConfigItem:uiCustomConfigItem];
    } else {
        BDFaceBaseKitUICustomConfigItem *uiCustomConfigItem = [[BDFaceBaseKitUICustomConfigItem alloc] initWithUIConfig];
        [[BDFaceBaseKitManager sharedInstance] setUiCustomConfigItem:uiCustomConfigItem];
    }
    //设置默认动作活体提示参数
    BDFaceBaseKitLivenessTipCustomConfigItem *tipCustomConfigItem = [[BDFaceBaseKitLivenessTipCustomConfigItem alloc] initWithLivenessTipConfig];
    [[BDFaceBaseKitManager sharedInstance] setFaceSdkCustomLivenessTipConfig:tipCustomConfigItem];
    paramsCustomConfigItem.isLivenessType = [AdminInfo.shareInfo.enableLiveness isEqualToString:@"1"];
    /// 设置licence_id 和license_name
    [[BDFaceBaseKitManager sharedInstance] initCollectWithLicenseID:FACE_LICENSE_ID andLocalLicenceName:FACE_LICENSE_NAME andExtradata:@{} callback:^(BDFaceInitRemindCode code, NSDictionary *extradata) {
        NSLog(@"%@",FACE_LICENSE_ID);
        NSLog(@"%@",FACE_LICENSE_NAME);
        NSLog(@"人脸初始化结果：%ld", (long)code);
    }];
    // 初始化设置的默认配置阈值参数
    [BDFaceAdjustParamsTool setDefaultConfig];
}

/*
 OCR SDK初始化
 */
- (void)initOcrSDK {
    NSString *licenseFile = [[NSBundle mainBundle] pathForResource:FACE_API_ORC_KEY ofType:FACE_SECRET_OCR_KEY];
    NSData *licenseFileData = [NSData dataWithContentsOfFile:licenseFile];
    [[AipOcrService shardService] authWithLicenseFileData:licenseFileData];
    NSLog(@"ocr sd version: %@", [AipOcrService ocrSdkVersion]);
}

/**
 6.4实名认证明镜SDK层调用
 */
- (void)checkFaceAction:(NSDictionary *)parameters {
    __weak typeof(self) this = self;
    [self startCheckFace:parameters response:^(int code, NSDictionary *callBack) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 0 表示成功
            if (code == 0) {
                NSDictionary *responseDic = callBack[BDFaceLogicServiceReturnKeyForResultData];
                [this showRequestSuccessResult:responseDic];
            } else {
                NSString *errorMessage = callBack[BDFaceLogicServiceReturnKeyForResultMsg];
                [this showMainStepFailResult:errorMessage];
            }
            
        });
    }];
}

// 6.3实名认证SDK层调用
//- (void)checkFaceAction:(NSMutableDictionary *)parameters {
//    __weak typeof(self) this = self;
//    [self startCheckFace:parameters response:^(int code, NSDictionary *callBack) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            // 0 表示成功
//            if (code == 0) {
//                NSDictionary *responseDic = callBack[BDFaceLogicServiceReturnKeyForResultData];
//                [this showRequestSuccessResult:responseDic];
//            } else {
//                NSString *errorMessage = callBack[BDFaceLogicServiceReturnKeyForResultMsg];
//                [this showMainStepFailResult:errorMessage];
//            }
//
//        });
//    }];
//}

/**
 * 6.3结果回调成功展示逻辑
 */
//- (void)showRequestSuccessResult:(NSDictionary *)responseDic {
//        BDFaceVerificationController *verificationController = (BDFaceVerificationController *)self.navigationController.topViewController;
//        NSDictionary *errorDic = responseDic[@"error_code"];
//        int riskLevel = [responseDic[@"risk_level"] intValue];
//        if (errorDic == nil) {
//            NSString *base64Image = [responseDic objectForKey:@"dec_image"];
//            if (base64Image) {
//                NSData* data = [[NSData alloc] initWithBase64EncodedString:base64Image options:NSDataBase64DecodingIgnoreUnknownCharacters];
//                UIImage *decode_image = [UIImage imageWithData:data];
//
//            }
//            if (responseDic[@"result"][@"verify_status"]) {
//
//                if ([responseDic[@"result"][@"verify_status"] intValue] == 1) {
//                    [verificationController showBDFaceFail];
//                } else if ([responseDic[@"result"][@"verify_status"] intValue] == 2) {
//                    [verificationController showBDFaceFailGongan];
//                } else {
//                    // 如果在线活体分数大于 最低的本地传的分数，那么通过
//                    if ([responseDic[@"result"][@"score"] floatValue] > [BDConfigDataService riskScore]) {
//                        if (riskLevel == 1 || riskLevel == 2) {
//                            NSString *msg = [NSString stringWithFormat:@"risk_tag : %@",responseDic[@"risk_tag"][0]];
//                            [verificationController showBDFaceLiveFail: @""];
//                        } else {
//                            [verificationController showBDFaceSuccess];
//                        }
//                    } else {
//                        // 分数过低的时候，点击重新采集，可以执行重新采集行为
//                        [verificationController showBDFaceLiveFail:@"在线验证失败，分数过低"];
//                    }
//                }
//            }
//        } else {
//            int code = [responseDic[@"error_code"] intValue];
//            BDFaceVerificationController *vc = (BDFaceVerificationController *)self.navigationController.topViewController;
//            [vc showServerError:code riskLevel:riskLevel];
//        }
//}

// 6.3人脸核验失败结果逻辑
//- (void)showMainStepFailResult:(NSString *)errorMessage {
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//        // 如果topController是人脸检测loading界面，那么先退出
//        if ([self.navigationController.topViewController isKindOfClass: BDFaceVerificationController.class]) {
//            [self.navigationController popViewControllerAnimated:NO];
//        }
//        UIViewController *baseController = self.navigationController.topViewController;
//        [BDFaceToastView showToast:baseController.view text:errorMessage];
//    });
//}


/**
 6.4人脸对比调用明镜层逻辑
 */
- (void)checkFaceMatchAction:(NSDictionary *)parameters {
    __weak typeof(self) this = self;
    [self.logicService startCheckLiveCommonAction:parameters callBack:^(int resultCode, NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 0 表示成功
            if (resultCode == 0) {
                // 跳转自定义结果页面
                NSDictionary *responseDic = resultDic[BDFaceLogicServiceReturnKeyForResultData];
                [this showMatchSuccessResult:responseDic];
            } else {
                NSString *errorMessage = resultDic[BDFaceLogicServiceReturnKeyForResultMsg];
                [this showMainStepFailResult:errorMessage];
            }
            
        });
    }];
}

/**
 6.4人脸对比结果数据判断
 */
- (void)showMatchSuccessResult:(NSDictionary *)responseDic {
    BDFaceVerificationController *verificationController = (BDFaceVerificationController *)self.navigationController.topViewController;
    int code = [responseDic[@"error_code"] intValue];
    if (code == 0) {
        [verificationController showBDFaceSuccess];
    } else {
        int code = [responseDic[@"error_code"] intValue];
        BDFaceVerificationController *vc = (BDFaceVerificationController *)self.navigationController.topViewController;
        [vc showServerError:code];
    }
}

/**
 6.4人脸实名认证核验前处理逻辑示例代码参考
 */
- (void)startLiveCheck {
    
    
    // 活体检测，包含本地检测和云端检测
    
    NSDictionary *tokenDic = @{BDFaceLogicServiceTokenKey : self.verifyToken ?: @"", @"match_source" : @(2)};
    __weak typeof(self) this = self;
    self.logicService.showLoadingAction = ^(void) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [this showCheckLiveLoadingAction];
        });
    };
    [self.logicService startCheckLiveCommonAction:tokenDic callBack:^(int resultCode, NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 0 表示成功
            if (resultCode == 0) {
                NSDictionary *responseDic = resultDic[@"data"];
//                if (responseDic[@"dec_image"]) {
//                    NSString *imgStr = responseDic[@"dec_image"];
//                    [self.viewModel requestAttendence:[UIImage imageWithData:[imgStr dataUsingEncoding:NSUTF8StringEncoding]]];
//                    [self.navigationController popViewControllerAnimated:YES];
//                } else {
//                    [self showCheckLiveFailResult:[NSString stringWithFormat:@"%@",responseDic]];
//                }
                DLog(@"%@",responseDic);
                if (responseDic[@"log_id"]) {
                    NSString *log_id = responseDic[@"log_id"];
                    [self.viewModel requestLivenessAttendenceLogId:log_id];
                    [self.navigationController popViewControllerAnimated:YES];
                } else {
                    [self showCheckLiveFailResult:[NSString stringWithFormat:@"%@",responseDic]];
                }
            } else {
                NSString *errorMessage = resultDic[BDFaceLogicServiceReturnKeyForResultMsg];
                [self showCheckLiveFailResult:errorMessage];
            }
            
        });
    }];
    
}

/**
 在线图片活体
 */
- (void)showCheckLiveLoadingAction {
    BDFaceVerificationController *avc = [[BDFaceVerificationController alloc] init];
    [self.navigationController pushViewController:avc animated:YES];
}

/**
 * 下面的decode_image是最终解密的照片
 */
- (void)showCheckLiveRequestSuccessResult:(NSDictionary *)responseDic {
    BDFaceVerificationController *verificationController = (BDFaceVerificationController *)self.navigationController.topViewController;
    NSDictionary *errorDic = responseDic[@"error_code"];
    int riskLevel = [responseDic[@"risk_level"] intValue];
    if (errorDic == nil) {
        NSString *base64Image = nil;
        NSArray *base64ImageArray = [responseDic objectForKey:@"dec_image"];
        if ([base64ImageArray isKindOfClass:[NSArray class]]) {
            NSArray *tempArray = (NSArray *)base64ImageArray;
            if (tempArray.count > 0) {
                base64Image = tempArray[0];
            }
        }
        if (base64Image) {
            NSData* data = [[NSData alloc] initWithBase64EncodedString:base64Image options:NSDataBase64DecodingIgnoreUnknownCharacters];
            /// 这个是解密出来的最终的识别的图片
            UIImage *decode_image = [UIImage imageWithData:data];
        }
        if([responseDic[@"success"] boolValue]) {
            if ([responseDic[@"result"][@"liveness_score"] floatValue] > 0.8) {
                if (riskLevel == 1 || riskLevel == 2) {
                    [verificationController showBDFaceLiveFail:@""];
                } else {
                    [verificationController showBDFaceSuccess];
                }
            } else {
                // 分数过低的时候，点击重新采集，可以执行重新采集行为
                [verificationController showBDFaceLiveFail:@"在线验证失败，分数过低"];
            }
        } else {
            [verificationController showBDFaceFail];
            NSString *msg = responseDic[@"message"];
            NSString *msgCode = responseDic[@"code"];
            NSString *msg_code = [NSString stringWithFormat:@"%@ %@", msgCode, msg];
            [BDFaceToastView showToast:[UIApplication sharedApplication].keyWindow text: msg_code];
        }
        
    }else {
        int code = [responseDic[@"error_code"] intValue];
        BDFaceVerificationController *vc = (BDFaceVerificationController *)self.navigationController.topViewController;
        [vc showServerError:code];
    }
}

- (void)showCheckLiveFailResult:(NSString *)errorMessage {
    UIViewController *baseController = self.navigationController.viewControllers[0];
    [self.navigationController popViewControllerAnimated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [BDFaceToastView showToast:baseController.view text:errorMessage];
    });
}



/**
 实名认证方案
 */
- (void)startCheckFace:(NSDictionary *)dic response:(void(^)(int code, NSDictionary *callBack))response {
    NSString *name = dic[BDIDInfoCollectControllerNameKey];
    NSString *cardNumber = dic[BDIDInfoCollectControllerIdNumberKey];
    NSNumber *cardType = dic[BDIDInfoCollectControllerCarTypeKey];
    NSString *tokenString = dic[BDFaceLogicServiceTokenKey];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:dic];
    {
        // 删除从OCR传递过来的，保留其他值。
        [parameters removeObjectForKey:BDIDInfoCollectControllerNameKey];
        [parameters removeObjectForKey:BDIDInfoCollectControllerIdNumberKey];
        [parameters removeObjectForKey:BDIDInfoCollectControllerCarTypeKey];
        [parameters removeObjectForKey:BDFaceLogicServiceTokenKey];
    }
    parameters[BDFaceLogicServiceNameKey] = name ?: @"";
    parameters[BDFaceLogicServiceCardNumberKey] = cardNumber ?: @"";
    parameters[BDFaceLogicServiceTokenKey] = tokenString ?: @"";
    // 默认身份证识别
    parameters[BDFaceLogicServiceCardTypeKey] = cardType ?: @(0);
    [self.logicService startCheckLiveCommonAction:parameters callBack:^(int resultCode, NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response) {
                response(resultCode, resultDic);
            }
        });
    }];
}

/**
 图片对比方案
 */
- (void)startCheckFaceMatch:(NSDictionary *)dic response:(void(^)(int code, NSDictionary *callBack))response {
    NSString *tokenString = dic[BDFaceLogicServiceTokenKey];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:dic];
    {
        // 删除从OCR传递过来的，保留其他值。
        [parameters removeObjectForKey:BDIDInfoCollectControllerNameKey];
        [parameters removeObjectForKey:BDIDInfoCollectControllerIdNumberKey];
        [parameters removeObjectForKey:BDIDInfoCollectControllerCarTypeKey];
        [parameters removeObjectForKey:BDFaceLogicServiceTokenKey];
    }
    parameters[BDFaceLogicServiceTokenKey] = tokenString ?: @"";
    [self.logicService startCheckLiveCommonAction:parameters callBack:^(int resultCode, NSDictionary * _Nonnull resultDic) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response) {
                response(resultCode, resultDic);
            }
        });
    }];
}

- (void)showLoadingAction {
    BDFaceVerificationController *avc = [[BDFaceVerificationController alloc] init];
    [self.navigationController pushViewController:avc animated:YES];
}

/**
 * 6.4实名认证下面的decode_image是最终解密的照片
 */
- (void)showRequestSuccessResult:(NSDictionary *)responseDic {
    BDFaceVerificationController *verificationController = (BDFaceVerificationController *)self.navigationController.topViewController;
    int code = [responseDic[@"error_code"] intValue];
    if (code == 0) {
        [verificationController showBDFaceSuccess];
    } else {
        int code = [responseDic[@"error_code"] intValue];
        BDFaceVerificationController *vc = (BDFaceVerificationController *)self.navigationController.topViewController;
        [vc showServerError:code];
    }
}

// 6.4 实名认核验证失败逻辑
- (void)showMainStepFailResult:(NSString *)errorMessage {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 如果topController是人脸检测loading界面，那么先退出
        if ([self.navigationController.topViewController isKindOfClass: BDFaceVerificationController.class]) {
            [self.navigationController popViewControllerAnimated:NO];
        }
        UIViewController *baseController = self.navigationController.topViewController;
        [BDFaceToastView showToast:baseController.view text:errorMessage];
    });
}

@end
